package com.neusoft.elmboot.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.elmboot.common.properties.JwtProperties;
import com.neusoft.elmboot.common.result.Result;
import com.neusoft.elmboot.common.utils.JwtUtil;
import com.neusoft.elmboot.po.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {

    public static final String [] IGNORE_AUTHORIZE_URLS = {"/users/info"};

    private static final String adminSecretKey = "elm";
    private long adminTtl = 7200000;
    private String adminTokenName = "elm-token";

    public JwtLoginFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher(defaultFilterProcessesUrl));
        setAuthenticationManager(authenticationManager);
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        //转换数据格式
        UserEntity userEntity = new ObjectMapper().readValue(httpServletRequest.getInputStream(), UserEntity.class);

        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(userEntity.getUserName(),userEntity.getPassword()));


    }


    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        Map<String,Object> clams = new HashMap<>();
        Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
        UserEntity u = null;
        if(null != authResult && authResult.getPrincipal() instanceof  UserEntity) {
            u = (UserEntity)authResult.getPrincipal();
        }
        StringBuffer as = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            as.append(authority.getAuthority()).append(",");
        }
        String authStr = "";
        if (as.length()>0) {
            authStr = as.substring(0,as.length()-1);
        }
        clams.put("authorities",authorities);
        clams.put("userId",u.getId());
        clams.put("userName",u.getUserName());
        //生成jwt
        String jwt = JwtUtil.createJWT(adminSecretKey, adminTtl, clams);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("user",u);
        retMap.put("token", jwt);
        Result x = Result.success(retMap);

        out.write(new ObjectMapper().writeValueAsString(x));
        out.flush();
        out.close();


    }
}
